package com.my.ext.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.my.ext.entity.Org;
import com.my.ext.entity.User;
import com.my.ext.service.IOrgService;
import com.my.ext.service.IUserService;
import com.my.ext.utils.ResultObject;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = { "/api/user", "/user" }, method = { RequestMethod.GET, RequestMethod.POST })
public class UserController {

	@Autowired
	IUserService service;

	@Autowired
	IOrgService orgService;

	@RequestMapping("/login")
	@ResponseBody
	@ApiOperation(value = "2.1 小程序用户登陆", notes = "小程序登录过程")
	public ResultObject login(String code, @RequestParam(value = "org", required = false, defaultValue = "0") int org) {
		ResultObject obj = new ResultObject();
		obj.setStatus(1);
		User u = service.authWX(code);
		Org o = orgService.findOrgById(org);
		Map<String, Object> map = new HashMap<>();
		System.out.println(u);
		if (u != null) {
			map.put("openid", u.getOpenid());
			if (u.getOrg() != null) {
				map.put("orgid", u.getOrg().getId());
				map.put("orgname", u.getOrg().getOrgname());
				map.put("userid", u.getId());
			} else {
				if (o == null) {
					if (u.getOrg() != null) {
						map.put("orgid", u.getOrg().getId());
						map.put("orgname", u.getOrg().getOrgname());
						map.put("userid", u.getId());
					} else {
						obj.setStatus(0);
						obj.setInfo("错误：没有组织");
					}
				} else {
					map.put("orgid", o.getId());
					map.put("orgname", o.getOrgname());
					map.put("userid", u.getId());
				}
			}

		}
		obj.setData(map);
		return obj;
	}

	@RequestMapping("/joinGroup")
	public ResultObject joinGroup(@RequestParam(value = "org", defaultValue = "0") int org,
			@RequestParam(value = "group", defaultValue = "0") int group, String name, String code, String openid) {
		ResultObject obj = new ResultObject();
		try {
			int i = service.updateUser(org, group, name, code, openid);
			System.out.println("日志：" + i);
			if (i == 1) {
				User u = service.getUserByOpenid(openid);
				obj.setStatus(1);
				obj.setData(u);
			} else {
				obj.setStatus(0);
				obj.setInfo("输入有错误，请确定您的用户名与组织账号");
			}
		} catch (Exception e) {
			e.printStackTrace();
			obj.setStatus(0);
			obj.setInfo("输入有错误，请确定您的用户名与组织账号");
		}
		return obj;
	}

}
